﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;

namespace iOak.Data.Helpers
{
    public class SqlScriptBuilder
    {
        public static void BuildCreateCommand(ref SqlCommand dbCommand)
        {
            StringBuilder fieldsBuilder = new StringBuilder();
            StringBuilder valuesBuilder = new StringBuilder();
            string outputparm = string.Empty;
            string fieldname = string.Empty;
            foreach (SqlParameter p in dbCommand.Parameters)
            {
                if (p.Direction == ParameterDirection.Output) continue;

                fieldname = p.ParameterName.Substring(1);
                fieldsBuilder.Append(fieldname).Append(",");
                valuesBuilder.Append("@").Append(fieldname).Append(",");

                if (p.Value == null)
                {
                    p.Value = DBNull.Value;
                }
            }

            fieldsBuilder = fieldsBuilder.Remove(fieldsBuilder.Length - 1, 1);
            valuesBuilder = valuesBuilder.Remove(valuesBuilder.Length - 1, 1);

            dbCommand.CommandText = String.Format(dbCommand.CommandText, fieldsBuilder, valuesBuilder);
        }

        public static void BuildUpdateCommand(ref SqlCommand dbCommand)
        {
            StringBuilder setsBuilder = new StringBuilder();

            string fieldname = string.Empty;
            foreach (SqlParameter p in dbCommand.Parameters)
            {
                if (p.ParameterName.StartsWith("@"))
                {
                    fieldname = p.ParameterName.Substring(1);
                }
                else
                {
                    fieldname = p.ParameterName;
                }

                setsBuilder.Append(fieldname).Append(" = @").Append(fieldname).Append(",");

                // 转换Null ->DBNull.Value
                if (p.Value == null)
                {
                    p.Value = DBNull.Value;
                }
            }

            setsBuilder = setsBuilder.Remove(setsBuilder.Length - 1, 1);

            dbCommand.CommandText = String.Format(dbCommand.CommandText, setsBuilder);
        }
    }
}
